﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TestClientApp
{
    public partial class Form1 : Form
    {
        Socket Client;

        public Form1()
        {
            InitializeComponent();

            IPHostEntry localMachineInfo = Dns.GetHostEntry(Dns.GetHostName());
            for (int i = 0; i < localMachineInfo.AddressList.Length; i++)
            {
                if (localMachineInfo.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    IPCombo.Items.Add(localMachineInfo.AddressList[i].ToString());
            }
        }

        private void ConnectBtn_Click(object sender, EventArgs e)
        {
            if (IPCombo.SelectedIndex==-1)
            {
                State.Text += "IP not selected";
                return;
            }
            int port;
            try
            {
                port = int.Parse(PortTBox.Text);
            }
            catch
            {
                State.Text = "port field is empty";
                return;
            }
            State.Text = "all is OK. connecting";
            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(IPCombo.SelectedItem.ToString()), port);
            Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                WriteLog(string.Format("Trying to connect {0}:{1}", serverEndPoint.Address.ToString(), serverEndPoint.Port.ToString()));
                Client.Connect(serverEndPoint);
                WriteLog("Connected");
                Thread ac = new Thread(Hear);
                ac.IsBackground = true;
                ac.Start();
                ConnectPanel.Visible = false;
                SendPanel.Location = new Point(ConnectPanel.Location.X, ConnectPanel.Location.Y);
                SendPanel.Visible = true;
            }
            catch
            {
                WriteLog("Error: Failed to connect");
                State.Text = "can't connet to remote server";
            }
        }

        private void Hear(object arg)
        {
            byte[] buf = new byte[256];
            try
            {
                while (true)
                {
                    if (Client.Receive(buf) > 0)
                    {
                        string msg = Encoding.ASCII.GetString(buf);
                        WriteLog(string.Format("Received: {0}", msg));
                        msg = msg.Substring(0, msg.IndexOf(@"\EOM"));
                    }
                }
            }
            catch
            {
                WriteLog("Error: Disconnected");
            }
        }

        private void SendBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (Client != null)
                {
                    string msg = MsgTBox.Text + @"\EOM";
                    WriteLog("Trying to send message: " + msg);
                    Client.Send(Encoding.ASCII.GetBytes(msg));
                    WriteLog("Sent: " + msg);
                }
            }
            catch
            {
                WriteLog("Error: Failed to send message");
                State.Text = "not connected";
                ConnectPanel.Visible = true;
                SendPanel.Visible = false;
            }
        }

        private void WriteLog(string msg)
        {
            string[] s = new string[1];
            s[0] = string.Format("{0}: {1}", DateTime.Now.ToString(), msg);
            System.IO.File.AppendAllLines(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log.txt"), s);
        }

    }
}
